'use client';

import { useLocale } from 'next-intl';
import { usePathname } from 'next/navigation';
import {
  locales,
  localeNames,
  localeFlags,
  type Locale,
  defaultLocale,
} from '@/i18n/config';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';

export function LanguageSwitcher() {
  const locale = useLocale() as Locale;
  const pathname = usePathname();

  const handleLocaleChange = (newLocale: string) => {
    // 获取当前路径，移除任何语言前缀
    let pathWithoutLocale = pathname;

    // 移除当前语言前缀（如果存在）
    for (const loc of locales) {
      if (pathname.startsWith(`/${loc}/`) || pathname === `/${loc}`) {
        pathWithoutLocale = pathname.slice(`/${loc}`.length) || '/';
        break;
      }
    }

    // 确保路径以 / 开头
    if (!pathWithoutLocale.startsWith('/')) {
      pathWithoutLocale = '/' + pathWithoutLocale;
    }

    // 构建新的URL
    let newUrl: string;
    if (newLocale === defaultLocale) {
      // 默认语言：不添加前缀
      newUrl = pathWithoutLocale;
    } else {
      // 其他语言：添加语言前缀
      newUrl = `/${newLocale}${pathWithoutLocale === '/' ? '' : pathWithoutLocale}`;
    }

    // 强制页面重新加载以确保路由正确处理
    window.location.href = newUrl;
  };

  return (
    <Select value={locale} onValueChange={handleLocaleChange}>
      <SelectTrigger className="w-[140px]">
        <SelectValue>
          <div className="flex items-center gap-2">
            <span>{localeFlags[locale]}</span>
            <span>{localeNames[locale]}</span>
          </div>
        </SelectValue>
      </SelectTrigger>
      <SelectContent>
        {locales.map(loc => (
          <SelectItem key={loc} value={loc}>
            <div className="flex items-center gap-2">
              <span>{localeFlags[loc]}</span>
              <span>{localeNames[loc]}</span>
            </div>
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}
